<?php
$em = require __DIR__ . '/../example/em.php';

use Service\UserManager;
$manager = new UserManager($em);
if (isset($_GET['id'])) {
    $decode = $_GET['id']/22;
    $decode = $decode-79988;    
    $manager = new UserManager($em);
    $user = $manager->getEntity($decode);
} else {
    $user = $manager->getEntity($user->getId());
}
$session_data = unserialize($_SESSION['auth']);
$admin_id=$session_data->getId();
//        echo '<pre>';
//var_dump($user->getParent()->getId());
//var_dump($user->getParent()->getName());
//var_dump($user->getGroup()->getId());
//var_dump($user->getChildren()->count());
//echo '</pre>';
//include ($_SERVER['DOCUMENT_ROOT'].'/jbdump/init.php');
//jbdump($user->getParent(), 0, 'myLoveVariable');
//jbdump($user->getChildren(), 0, 'myLoveVariable');
?>
<!-- aditional stylesheets -->
        <!-- x-editable -->
            <link rel="stylesheet" href="template/js/lib/x-editable/bootstrap-editable/css/bootstrap-editable.css">
<!-- enchanced select box, tag handler -->
            <link rel="stylesheet" href="template/js/lib/select2/select2.css">
        <!-- main content -->
            <div class="container">
                <div class="row-fluid">
                    <div class="span12">
                        <div class="w-box">
                            <div class="w-box-header">
                                <h4>Профиль пользователя</h4>
                                <div class="btn-group" style="margin-left: 20px;">
                                    <a href="#" class="btn btn-inverse btn-mini " id="enable" title="Редактировать">Редактировать</a>
                                    <!--<a href="#" class="btn btn-inverse btn-mini " id="balance_up" title="Пополнить баланс">Пополнить баланс</a>-->
                                </div>
                            </div>
                            <div class="w-box-content cnt_a">
                                <table class="table table-bordered table-striped" id="user_profile">
                                    <tbody>
                                        <tr>
                                            <td width="15%">Баланс</td>
                                            <td width="50%"><?php echo $user->getBalance(); ?></td>
                                        </tr>
                                        <tr>
                                            <td width="15%">Бонусный процент</td>
                                            <td width="50%">
                                                <?php if ($admin_id==1) : ?>
                                                    <a data-original-title="Бонусный процент" data-pk="<?php echo $user->getId(); ?>" data-type="text" id="bonus" href="#"><?php echo $user->getBonus(); ?>%&nbsp;<i style="display: none" class="splashy-document_letter_edit"></i></a>
                                                <?php else: ?>
                                                    <?php echo $user->getBonus().'%'; ?>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td width="15%">Логин</td>
                                            <td width="50%"><a data-original-title="Введите логин" data-pk="<?php echo $user->getId(); ?>" data-type="text" id="name" href="#"><?php echo $user->getName(); ?>&nbsp;<i style="display: none" class="splashy-document_letter_edit"></i></a></td>
                                        </tr>
                                        <tr>
                                            <td width="15%">Имя пользователя</td>
                                            <td width="50%"><a data-original-title="Введите имя пользователя" data-pk="<?php echo $user->getId(); ?>" data-type="text" id="fullname" href="#"><?php echo $user->getFullName(); ?>&nbsp;<i style="display: none" class="splashy-document_letter_edit"></i></a></td>
                                        </tr>
                                        <tr>
                                            <td>Группа</td>
                                            <td>

                                                <?php if ($admin_id==1) : ?>
                                                <?php if ($user->getChildren()->count()>0){
                                                        echo $user->getGroup()->getName().'&nbsp;<a id="info_1" title="Для смены группы переместите ваших субагентов" href="#" <i style="display: none" class="splashy-slider_no_pointy_thing"></i></a>';
                                                    }else{
                                                        echo '<a data-original-title="Выберите группу" data-source="ajax/getGroup.php" data-value="1" data-pk="'. $user->getId().'" data-type="select" id="group_user" href="#">'. $user->getGroup()->getName().'&nbsp;<i style="display: none" class="splashy-document_letter_edit"></i></a>';
                                                    }
                                                ?>

                                                <?php else: ?>
                                                <?php echo $user->getGroup()->getName(); ?>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>Родитель</td>
                                            <td>
                                                <?php if ($admin_id==1 and $user->getGroup()->getId()==3) : ?>
                                                <a data-original-title="Выберите родителя" data-source="ajax/getUserAgent.php" data-value="1" data-pk="<?php echo $user->getId(); ?>" data-type="select" id="user_parent" href="#"><?php echo $user->getParent()->getName(); ?>&nbsp;<i style="display: none" class="splashy-document_letter_edit"></i></a>
                                                <?php else: ?>
                                                <?php echo $user->getParent()->getName(); ?>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>Пароль</td>
                                            <td>
                                                <div class="row-fluid">
                                                    <div class="span4">
                                                        <input type="password" id="password_meter" class="span12">
                                                        <div id="pwdMeter" class="progress progress-danger">
                                                            <div class="bar" style="width: 0%"></div>
                                                            <span class="pwdText"></span>
                                                        </div>
                                                    </div>
                                                    <div class="span4">
                                                        <div id="pwdGenerator"></div>
                                                        <button id="set_pass" type="submit" class="btn btn-beoro-3">Применить</button>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td width="15%">E-mail</td>
                                            <td width="50%"><a data-original-title="Введите e-mail" data-pk="<?php echo $user->getId(); ?>" data-type="text" id="email" href="#"><?php echo $user->getEmail(); ?>&nbsp;<i style="display: none" class="splashy-document_letter_edit"></i></a></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($admin_id==1) : ?>
                <?php if ($user->getGroup()->getId()!==3) : ?>
                <div class="row-fluid">
                    <div class="w-box hideable" id="n_multiselect">
                        <div class="w-box-header">
                            <h4>Смена уровня</h4>
                        </div>
                        <div class="w-box-content cnt_a content-hide">
                            <div class="row-fluid">
                                <div class="span6">
                                    <div class="span6">
                                    </div>
                                    <div class="span6">
                                        <select id="transfer_user" class="span11">
                                            <option value=""></option>
                                        </select>
                                    </div>
                                    <select id="public-methods" multiple="multiple"></select>

                                    <div class="btn-toolbar">
                                        <div class="btn-group">
                                            <a href="javascript:void(0)" id="select-all" class="btn btn-mini">Select all</a>
                                            <a href="javascript:void(0)" id="deselect-all" class="btn btn-mini">Deselect all</a>
                                            <a href="javascript:void(0)" id="save" class="btn btn-mini">Сохранить</a>
                                        </div>
                                    </div>
                                    <br>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                <?php endif; ?>
                </div>
            <div class="footer_space"></div>
        </div>
<!-- 2col multiselect -->
<script src="template/js/lib/multi-select/js/jquery.multi-select.min.js"></script>
<script src="template/js/lib/multi-select/js/jquery.quicksearch.min.js"></script>
<!-- enchanced select box, tag handler -->
<script src="template/js/lib/select2/select2.min.js"></script>
<!-- bootbox -->
<script src="template/js/lib/bootbox/bootbox.min.js"></script>
<!-- masked inputs -->
<script src="template/js/lib/jquery-inputmask/jquery.inputmask.min.js"></script>
<script src="template/js/lib/jquery-inputmask/jquery.inputmask.extensions.js"></script>
<script src="template/js/lib/jquery-inputmask/jquery.inputmask.date.extensions.js"></script>

<script type="text/javascript">
    $.fn.hasAttr = function(name) {
        return this.attr(name) !== undefined;
    };

    $(document).ready(function() {
///////////////////////////////////////////////////
        if ($('#info_1').length) {
            $('#info_1').powerTip({
                placement: 'sw'
            })
        }

        $('#select-all').click(function () {
            $('#public-methods').multiSelect('select_all');
            return false;
        });
        $('#deselect-all').click(function () {
            $('#public-methods').multiSelect('deselect_all');
            return false;
        });
        $('#select-all').html('Выбрать все');
        $('#deselect-all').html('Отменить выбор');

        $("#info_1, .w-box-header h4").click(function () {
            $(".icon-plus").trigger('click');
            $('html, body').animate({scrollTop:$(document).height()}, 'slow');
            return false;
        });

        $("#transfer_user").select2({
            placeholder: "Кому отдаем",
            allowClear: true
        }).on("change", function (e) {
                    $('#s2id_transfer_user span').attr("id", e.val);
                });
        $("#s2id_transfer_user").css({
            "padding": "0 0 0 20px",
            "width": "275px"
        });
        $.post('ajax/manage_level.php', { method: "load_urer_list", id: <?php echo $user->getId(); ?> },function (data) {
            $('#public-methods').html(data);
        }).done(function () {
                $('#public-methods').multiSelect();
            });
        $.post('ajax/manage_level.php', { method: "load_page"}, function (data) {
            $('#transfer_user').html(data);
        });
    $("#save").click(function (e) {
        if(!$('#s2id_transfer_user span').hasAttr('id')) {
            bootbox.alert("Выберите кому передавать!", function () {
                return true;
            });
        }else{
            var arrList = $('.ms-selection .ms-list li').map(function () {
                return $(this).attr('ms-value');
            }).get();
            if (arrList.length == 0) {
                e.preventDefault();
                bootbox.alert("Перенесите пользователей!", function () {
                    return true;
                });
            } else {
                var select_user = <?php echo $user->getId(); ?>;
                var transfer_user = $('#s2id_transfer_user span').attr("id");
                $.post('ajax/manage_level.php', { method: "save", id: arrList, select_user: select_user, transfer_user: transfer_user}, function (data) {
                }).done(function() {
                            bootbox.alert("Пользователи переданы!", function () {
                                //return true;
                                window.location.reload(true);
                            });
                        });
            }
        }
    });


    //defaults
        $.fn.editable.defaults.url = 'ajax/userProfile.php';

         //enable / disable
        $('#enable').click(function() {
            $('#user_profile .editable').editable('toggleDisabled');

            $('.splashy-document_letter_edit, .splashy-slider_no_pointy_thing').toggle('fast');
        });
        $('#bonus').editable('disable', {
            type: 'text'
        });
        $('#name').editable('disable', {
            type: 'text'
        });
        $('#fullname').editable('disable', {
            type: 'text'
        });
        $('#email').editable('disable', {
            type: 'text'
        });

        $('#group_user').editable({
            disabled: true,
            type: 'select',
            url: 'ajax/userProfile.php',
            showbuttons: true,
            source: function() {
                var result;
                $.ajax({
                    url: 'ajax/getGroup.php',
                    type: 'GET',
                    global: false,
                    async: false,
                    dataType: 'json',
                    success: function(data) {
                        result = data;
                    }
                });
                return result;
            },
            success: function(response, newValue) {
            //console.log(response, newValue);
                window.location.reload(true);
            }
        });

        $('#user_parent').editable('disable', {
            url: 'ajax/userProfile.php',
            showbuttons: false
        });

        $('#user_profile .editable').on('hidden', function(e, reason){
            if(reason === 'save' || reason === 'nochange') {
                var $next = $(this).closest('tr').next().find('.editable');
                if($('#autoopen').is(':checked')) {
                    setTimeout(function() {
                        $next.editable('show');
                    }, 300);
                } else {
                    $next.focus();
                }
            }
        });
        $("#password_meter").pwdMeter({
                    minLength: 6,
                    displayGeneratePassword: true,
                    generatePassText: 'Сгенерировать новый пароль',
                    randomPassLength: 16,
                    neutralText: "",
                    veryWeakText: "Очень слабый",
                    weakText: "Слабый",
                    mediumText: "Средний",
                    strongText: "Сложный",
                    veryStrongText: "Очень сложный"
        });
        $("#set_pass").click(function() {
            if ($("#password_meter").val()!=='') {
                $.post("ajax/userProfile.php", { name: "password", pk: <?php echo $user->getId(); ?>, value: $("#password_meter").val() },
                    function(data){
                        $('#pwdGenerator').append('<br><span id="Spn_NewPassword" class="NewPassword"></span>');
                        $('#Spn_NewPassword').text($("#password_meter").val());
                        $.sticky('Пароль изменен!', {autoclose: 6000, position: "top-center", type: "st-success"});
              })
            } else {
                $.sticky('Введите пароль!', {autoclose: 6000, position: "top-center", type: "st-error"});
                return false;
            }

        });
});
</script>